<?php

namespace App\Http\Controllers\Api;

use App\Api\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JWTAuth;


class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    public function login(Request $request)
    {
        $param = $request->only(['username', 'password']);
        if (!$token = auth('api')->attempt($param)) {
            abort(401);
        }

        return success($this->respondWithToken((string)$token));
    }

    public function me()
    {
        return success(auth('api')->user());
    }


    public function logout()
    {
        auth('api')->logout();

        return success();
    }

    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    public function addUser(Request $request)
    {
        $param             = $request->all(['username', 'password']);
        $param['password'] = password_hash($param['password'], PASSWORD_BCRYPT);
        $result            = User::query()->updateOrCreate(['username' => $param['username']], $param);
        abort_if(!$result, 400, '创建失败');

        return success($result);
    }


    protected function respondWithToken($token)
    {
        return [
            'access_token' => $token,
            'token_type'   => 'bearer',
            'expires_in'   => JWTAuth::factory()->getTTL() * 60,
        ];
    }
}
